package com.heima.user.controller.v1;

import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.LoginDto;
import com.heima.model.user.dtos.RegisterDto;
import com.heima.user.service.ApUserService;
import com.heima.user.util.SendSms;
import com.heima.user.util.ValidateCodeUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;

@RestController
@RequestMapping("/api/v1/login")
@Api(value = "app端用户控制器")
public class ApUserLoginController {
    @Autowired
    private ApUserService apUserService;

    /**
     * 用户登录
     * @param loginDto
     * @return
     */
    @PostMapping("/login_auth")
    @ApiOperation("用户登录")
    public ResponseResult login(@RequestBody LoginDto loginDto){
        return apUserService.login(loginDto);
    }

    /**
     * 请求生成验证码
     * @param
     * @return
     */
    @GetMapping("/sendMsg")
    @ApiOperation("生成验证码")
    public ResponseResult sendMsg(String phone,HttpSession session){
        //验证手机号长度是否符合长度
        if (phone.length()!=11){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //生成验证码
        String code = ValidateCodeUtils.generateValidateCode4String(4);
        SendSms.sendMsg(phone,code);
        //将验证码放入session中
        session.setAttribute("code",code);
        //设置session过期时间(10分钟)
        session.setMaxInactiveInterval(600);
        return ResponseResult.okResult(200,"发送成功");
    }


    /**
     * 验证验证码是否正确,是否允许注册
     * @param
     * @return
     */
    @GetMapping("/checkCode")
    @ApiOperation("验证验证码")
    public ResponseResult proRegister(String Msg,HttpSession session){
        //获取session中保存的验证码
        String code = session.getAttribute("code").toString();
        //判断验证码是否存在
        if (code==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"验证码已过期");
        }
        //校验验证码是否正确
        if(!code.equals(Msg)){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"验证码错误");
        }
        //将验证结果存入session
        session.setAttribute("result","1");
        return ResponseResult.okResult(200,"验证成功");
    }
    /**
     * 用户注册
     * @param registerDto
     * @return
     */
    @PostMapping("/register_auth")
    @ApiOperation("用户注册")
    public ResponseResult register(@RequestBody RegisterDto registerDto,HttpSession session){
        //获取验证信息
        String result = session.getAttribute("result").toString();
        if (result!="1"){
            //验证失败,是非法请求
            return ResponseResult.errorResult(AppHttpCodeEnum.NO_OPERATOR_AUTH,"无权限操作");
        }
        return apUserService.register(registerDto);
    }
}
